import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_splash_screen/flutter_splash_screen.dart';
import 'package:p_location/common/constant/sp_key.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/debug/debug_page.dart';
import 'package:p_location/home/home.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_constants.dart';
import 'package:p_location/net/net_listener.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:p_location/user/constants/user_http_url.dart';
import 'package:p_location/user/obj/obj_map_path.dart';
import 'package:p_location/user/obj/user_info.dart';
import 'package:p_location/user/res/building.dart';
import 'package:p_location/user/res/login_res.dart';
import 'package:p_location/user/res/module_info.dart';
import 'package:p_location/user/res/res_config_setting.dart';
import 'package:p_location/user/res/res_license_info.dart';
import 'package:p_location/user/ui/page_ip_config.dart';
import 'package:p_location/utils/navigator_util.dart';
import 'package:p_location/utils/net/trace_module_util.dart';
import 'package:p_location/utils/shared_preferences_util.dart';
import 'package:p_location/utils/string_util.dart';
import 'package:p_location/utils/toast_util.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> implements NetListener {
  String appName = "人员定位APP";
  final TextEditingController _accountController = new TextEditingController();
  final TextEditingController _passwordController = new TextEditingController();

  //登录高度
  final double height = 48;

  final double radius = 5;
  
  //登录按钮是否有效
  bool isEnable = false;

  //是否 密码明文显示
  bool isVisible = false;
  //焦点的监听
  FocusNode _passwordFocus = FocusNode();
  FocusNode _accountFocus = FocusNode();

  Future<void> pop() async {
    await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  }

  @override
  void onRequestError(CommonRes errorRes) {
    if (errorRes != null) {
      ToastUtil.showToast(errorRes.msg);
    }
  }

  @override
  void onRequestSuccess(Response response) {
    if (response != null && response.data != null) {
      var headerMap = response.headers.map;
      if (headerMap != null) {
        var authTokenList = headerMap["authToken"];
        if (authTokenList != null && authTokenList.length > 0) {
          DioHttpClient.addHeader("authToken", authTokenList[0]);
        }
      }
      DioHttpClient.addHeader("user-agent", "Dart/2.14 (dart:io)");
      print(response.headers["set-cookie"]);
      LoginRes loginRes = LoginRes.fromJson(response.data);
      Map<String, String> map = Map();
      map[SPKey.KEY_ACCOUNT] = _accountController.text;
      map[SPKey.KEY_PASSWORD] = _passwordController.text;
      SharedPreferenceHelp.save(map);
      UserInfo.mLoginRes = loginRes;
      if (loginRes != null &&
          loginRes.data != null &&
          loginRes.data.buildings != null &&
          loginRes.data.buildings.length > 0) {
        UserInfo.buildings = loginRes.data.buildings;
        if (loginRes.data.buildings.length == 1) {
          chooseBuilding(loginRes.data.buildings[0]);
        } else {
          showBottomSheet(loginRes.data.buildings);
        }
      } else {
        ToastUtil.showToast("该帐号没有可用的建筑");
      }
    }
  }

  @override
  void initState() {
    initCacheLoginInfo();
    super.initState();
    hideScreen();
//    _checkVersionUpdate();
  }

  ///关闭闪屏
  Future<void> hideScreen() async {
    Future.delayed(Duration(milliseconds: 1000), () {
      FlutterSplashScreen.hide();
      if (StringUtil.isEmpty(DioHttpClient.baseUrl)) {
        NavigatorUtil.push(context, PageIpConfig());
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false, //输入框抵住键盘
      appBar: _getAppBar(),
      body: Stack(
        children: [
          Column(
            children: <Widget>[
              FractionallySizedBox(
                widthFactor: 1,
                child: Container(
                    margin: EdgeInsets.only(top: 40, left: 40),
                    alignment: Alignment.topLeft,
                    child: GestureDetector(
                      onLongPress: () {
//                        NavigatorUtil.push(context, DebugPage());
                      },
                      child: Text(
                        appName,
                        style: TextStyle(fontSize: 30,fontWeight: FontWeight.w600),
                      ),
                    )),
              ),
              Container(
                margin: EdgeInsets.only(left: 30, right: 30, top: 40),
                child: TextField(
                  focusNode: _accountFocus,
                  controller: _accountController,
                  autofocus: false,
                  decoration: InputDecoration(
                      //prefixIcon: Icon(Icons.account_circle),
                      hintText: '请输入账号',
                      hintStyle: TextStyle(color: Colors.grey),
                      border: OutlineInputBorder(
                          borderSide: BorderSide.none,
                        borderRadius: BorderRadius.all(Radius.elliptical(10, 10),
                        )
                      ),
                      suffixIcon: Offstage(
                        offstage: StringUtil.isEmpty(_accountController.text),
                        child: IconButton(
                          onPressed: () {
                            _accountController.text = "";
                            _inputChange("");
                          },
                          icon: Icon(Icons.clear),
                        ),
                      ),
                    filled: true,  // 不然 fillColor 等 不生效
                    fillColor: Colors.grey.withOpacity(0.1),
                  ),
                  onChanged: _inputChange,
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 30, right: 30, top: 20),
                child: TextField(
                  focusNode: _passwordFocus,
                  controller: _passwordController,
                  obscureText: !isVisible,
                  decoration: InputDecoration(
                      //prefixIcon: Icon(Icons.lock),
                      hintText: '请输入密码',
                      hintStyle: TextStyle(color: Colors.grey),
                      suffixIcon: IconButton(
                        icon: isVisible
                            ? Icon(Icons.visibility)
                            : Icon(Icons.visibility_off),
                        onPressed: () {
                          setState(() {
                            isVisible = !isVisible;
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.elliptical(10, 10)),
                        borderSide: BorderSide.none,
                      ),
                    filled: true,  // 不然 fillColor 等 不生效
                    fillColor: Colors.grey.withOpacity(0.1),
                  ),
                  onChanged: _inputChange,
                ),
              ),
              Container(
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        //渐变位置
                        begin: Alignment.topRight, //右上
                        end: Alignment.bottomLeft, //左下
                        stops: [
                          0.0,
                          1.0
                        ], //[渐变起始点, 渐变结束点]
                        //渐变颜色[始点颜色, 结束颜色]
                        colors: [
                          Color.fromRGBO(56, 160, 253, 0.9),
                          Color.fromRGBO(26, 103, 250, 0.9)
                        ]),
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(radius),
                        topRight: Radius.circular(radius),
                        bottomLeft: Radius.circular(radius),
                        bottomRight: Radius.circular(radius))),
                margin: EdgeInsets.only(left: 30, right: 30, top: 40),
                height: height,
                child: FractionallySizedBox(
                  widthFactor: 1,
                  child: RaisedButton(
                    shape: new RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(radius),
                    ),
                    child: Text(
                      '登 录',
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                    onPressed: () {
                      if (isEnable) {
                        _accountFocus.unfocus();
                        _passwordFocus.unfocus();
                        login();
                      }
                      /*else {
                        ToastUtil.showToast('请填写账号信息');
                      }*/
                    },
                    //disabledColor: Colors.grey,
                    color: setColorsInLogin(isEnable),
                  ),
                ),
              ),
            ],
          ),
          Positioned(
              child: GestureDetector(
                onTap: () {
                  NavigatorUtil.push(context, PageIpConfig());
                },
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  alignment: Alignment.center,
                  child: Text(
                    "本地端用户配置入口",
                    style: TextStyle(color: Colors.blue, fontSize: 16),
                  ),
                ),
              ),
              bottom: 40)
        ],
      ),
    );
  }

  _getAppBar() {
    return AppBar(
      backgroundColor: Colors.white,
      brightness: Brightness.light,
      elevation: 0,
      /*title: Platform.isAndroid
          ? Container(
              child: GestureDetector(
                onTap: () async {
                  await pop();
                },
                */ /*child: Icon(
                  Icons.close,
                  color: Colors.blue,
                ),*/ /*
              ),
            )
          : Text(''),*/
    );
  }

  login() async {
    print("ipadrrdss");
    print(DioHttpClient.baseUrl);
    List<int> bytes = utf8.encode(_passwordController.text);
    String encodedStr = base64Encode(bytes);
    print(encodedStr);

    Map<String, dynamic> params = {};
    params['username'] = _accountController.text;
    params['password'] = encodedStr;
    await DioHttpClient.requestPost(
        context, 'app/identity/doLogin', params, this,
        contentType: NetConstants.POST_TYPE_FORM, loadingTip: '登录中...');
  }

  initCacheLoginInfo() async {
    SharedPreferenceHelp.read(SPKey.KEY_ACCOUNT).then((account) {
      setState(() {
        _accountController.text = account;
        _inputChange('');
        if (isEnable && !DioHttpClient.isEmptyToken()) {
//          login();
        }
      });
    });
    SharedPreferenceHelp.read(SPKey.KEY_PASSWORD).then((password) {
      setState(() {
        _passwordController.text = password;
        _inputChange('');
        if (isEnable && !DioHttpClient.isEmptyToken()) {
//          login();
        }
      });
    });

    String logoName = await SharedPreferenceHelp.read(SPKey.KEY_LOGO_NAME);
    debugPrint('logoName$logoName');
    if (StringUtil.isNotEmpty(logoName)) {
      setState(() {
        appName = logoName;
      });
    }

    String protocol = await SharedPreferenceHelp.read(SPKey.KEY_IP_PROTOCOL);
    String ipAddress = await SharedPreferenceHelp.read(SPKey.KEY_IP_ADDRESS);
    debugPrint('ipAddress$ipAddress');
    if (StringUtil.isNotEmpty(protocol) && StringUtil.isNotEmpty(ipAddress)) {
      setState(() {
        DioHttpClient.baseUrl = '$protocol$ipAddress';
      });
    }
  }

  Color setColorsInLogin(bool isEnable) {
    if (isEnable) return Colors.lightBlue;
    return Colors.grey;
  }

  _inputChange(String str) {
    setState(() {
      isEnable =
          _accountController.text != '' && _passwordController.text != '';
    });
  }

  showBottomSheet(List<Building> buildings) {
    showModalBottomSheet(
      shape: RoundedRectangleBorder(borderRadius:BorderRadius.vertical(top: Radius.elliptical(10, 8)),),
      context: context,
      builder: (context) => Container(
          height: (120 + buildings.length * 50.0 + 100),
          child: Column(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius:BorderRadius.vertical(top: Radius.elliptical(10, 8)),
                ),
                margin: EdgeInsets.fromLTRB(0, 0, 0,5),
                padding: EdgeInsets.symmetric(vertical: 15),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text('请选择建筑',style: TextStyle(fontSize: 15,color: Colors.grey),),
                    ])
              ),
              Expanded(
                  child: ListView.separated(
//            shrinkWrap: true,
//            physics: new NeverScrollableScrollPhysics(),
                      separatorBuilder: (BuildContext context, int index) =>
                          Divider(height: 0.5),
                      itemCount: buildings.length,
                      itemBuilder: (context, index) {
                        return _item(buildings[index]);
                      })),
              GestureDetector(
                onTap: (){
                  Navigator.of(context).pop();
                },
                child:Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, 10, 0, 8),
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.max,
                      children: [
                            Text('取消', style: TextStyle(fontSize: 20),),
                      ],
                    )),
              )

            ],
          )),
    );
  }

  _item(Building building) {
    return GestureDetector(
      onTap: () {
        try {
          DioHttpClient.addHeader("buildId", building.buildId);
          chooseBuilding(building);
        } on Exception catch (e) {
          print('捕获异常' + e.toString());
        }
      },
      child: Container(
        height: 50,
        color: Colors.white,
        alignment: Alignment.center,
        child: Text(building.buildName),
      ),
    );
  }

  chooseBuilding(Building building) async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        '${UserHttpUrl.CHOOSE_BUILDING_URL}?buildId=${building.buildId}',
        params,
        NetListenerImpl((response) {
          setState(() {
            if (response != null && response.data != null) {
              Map<String, String> buildInfo = {};
              buildInfo[SPKey.KEY_BUILD_ID] = building.buildId;
              buildInfo[SPKey.KEY_BUILD_NAME] = building.buildName;
              getNameSetting();
              getLicense(building.buildId);
              SharedPreferenceHelp.save(buildInfo);
              TraceModuleUtil(_accountController.text,"登录").requestTrace(context);
            }
          });
        }, (CommonRes errorRes) {
          if (errorRes != null) {
            ToastUtil.showToast(errorRes.msg ?? "请求异常");
          }
        }),
        loadingTip: "请求中...");
  }

  getLicense(String buildId) async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestGet(
        context,
        '${UserHttpUrl.GET_LICENCE}?buildId=$buildId',
        params,
        NetListenerImpl((response) {
          if (response != null && response.data != null) {
            ResLicenseInfo res = ResLicenseInfo.fromJson(response.data);
            if (res != null && res.data != null) {
                if(res.data.active){
                  Navigator.pushAndRemoveUntil(
                    context,
                    new MaterialPageRoute(builder: (context) => Home()),
                        (route) => route == null,
                  );
                }else{
                  ToastUtil.showToast("license已过期，请联系系统管理员");
                }
//              List<ModuleInfo> modules = res.data.modules;
//              if (modules != null) {
//                debugPrint('modules的size${modules.length}');
//                UserInfo.moduleInfos = modules;
//                ModuleInfo info =
//                    modules.firstWhere((element) => element.name == '车辆管理');
//                if (info != null && info.valid) {
//                  print("有效");
//                } else {
//                  print("无效");
//                }
//              }
            }
          }
        }, (CommonRes errorRes) {
          if (errorRes != null) {}
        }));
  }

  getNameSetting() async {
    await DioHttpClient.requestPost(
        context,
        UserHttpUrl.GET_NAME_SETTING,
        {},
        NetListenerImpl((response) {
          if (response != null && response.data != null) {
            ResConfigSetting setting = ResConfigSetting.fromJson(response.data);
            if (setting != null && setting.code == 0) {
              if (setting.data != null) {
                String configVal = setting.data.configVal;
                debugPrint('configVal$configVal');
                Map<String, String> configInfo = {};
                configInfo[SPKey.KEY_LOGO_NAME] = configVal;
                SharedPreferenceHelp.save(configInfo);
                savePathUrl(setting.data.tenentId, setting.data.orgCode);
              }
            }
          }
        }, (CommonRes errorRes) {}));
  }

  savePathUrl(int tenantId, String orgCode) {
    ObjMapPath.pathUrl = '${DioHttpClient.baseUrl}/map/$tenantId/$orgCode';
  }
}
